package com.atguigu.day04;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Felix
 * @date 2024/7/12
 * 该案例演示了将流中数据写到kafka---kafka连接器
 * 要想保证写入的一致性，需要做如下操作
 *      必须开启检查点
 *      .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
 *      .setTransactionalIdPrefix("xxx")
 *      检查点的超时时间 < 事务的超时时间 <= 事务最大的超时时间(15m)
 *      .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, 15*60*1000 + "")
 *      在消费端，应该设置消费的事务隔离级别为读已提交
 */
public class Flink09_Sink_Kafka {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流出来环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.将流中的数据写到kafka主题中
        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
                .setBootstrapServers("hadoop102:9092")
                .setRecordSerializer(
                        KafkaRecordSerializationSchema.builder()
                                .setTopic("first")
                                .setValueSerializationSchema(new SimpleStringSchema())
                                .build()
                )
                //.setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                //.setTransactionalIdPrefix("xxx")
                //.setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG, 15*60*1000 + "")
                .build();
        socketDS.print();
        socketDS.sinkTo(kafkaSink);
        //TODO 4.作业提交
        env.execute();
    }
}
